const db = uniCloud.database();
const UniID = require('uni-id-common');

exports.main = async (event, context) => {
  // 解析请求体，兼容 Apifox
  let body = event;
  if (event.body !== undefined) {
    try {
      body = JSON.parse(event.body);
    } catch (e) {
      return {
        code: 400,
        message: "请求体解析失败",
        error: e.message
      };
    }
  }

  // 参数提取
  const { uniIdToken, ...restFields } = body;

  // 校验 token 是否存在
  if (!uniIdToken) {
    return {
      code: 401,
      message: "缺少 uniIdToken"
    };
  }

  // 创建 uniID 实例并校验 token
  const uniIDIns = UniID.createInstance({ context });
  const tokenRes = await uniIDIns.checkToken(uniIdToken);

  if (!tokenRes.uid) {
    return {
      code: tokenRes.errCode || 403,
      message: tokenRes.message || "token 无效或已过期"
    };
  }

  const uid = tokenRes.uid;


	//字段白名单
	const ALLOWED_FIELDS = ['risk_level', 'age', 'gender'];
	//字段可选值
	const FIELD_VALUE_CONSTRAINTS = {
	  risk_level: ['低风险', '中风险', '高风险'],
	  gender: ['男', '女', '保密']
	};

	const updateFields = {};
	for (let key in restFields) {
	  if (ALLOWED_FIELDS.includes(key)) {
		const value = restFields[key];

		// 可选值约束校验
		const allowedValues = FIELD_VALUE_CONSTRAINTS[key];
		if (allowedValues && !allowedValues.includes(value)) {
		  return {
			code: 422,
			message: `字段 ${key} 的取值非法，应为: ${allowedValues.join(', ')}`
		  };
		}

		// age 特殊校验：必须为正整数
		if (key === 'age') {
		  const num = Number(value);
		  if (!Number.isInteger(num) || num <= 0) {
			return {
			  code: 422,
			  message: `字段 age 的值必须为正整数`
			};
		  }
		}

		updateFields[key] = value;
	  }
	}


  if (Object.keys(updateFields).length === 0) {
    return {
      code: 422,
      message: "未提供合法的更新字段，仅支持字段: " + ALLOWED_FIELDS.join(", ")
    };
  }
  
    // 查询用户信息，判断 is_consultant
    let userInfo;
    try {
      const userRes = await db.collection('uni-id-users').doc(uid).get();
      userInfo = userRes.data[0];
      if (!userInfo) {
        return {
          code: 404,
          message: "用户不存在"
        };
      }
      if (userInfo.is_consultant && userInfo.is_consultant !== 0) {
        return {
          code: 403,
          message: "token错误，这是咨询师的token"
        };
      }
    } catch (e) {
      return {
        code: 500,
        message: "查询用户信息失败",
        error: e.message
      };
    }
	
  // 更新数据库
  try {
    await db.collection('uni-id-users').doc(uid).update(updateFields);
    return {
      code: 0,
      message: "用户信息更新成功"
    };
  } catch (e) {
    return {
      code: 500,
      message: "数据库更新失败",
      error: e.message
    };
  }
};
